package afero

import (
	"os"
	"syscall"
	"time"
)

var _ Lstater = (*WriteOnlyFs)(nil)

type WriteOnlyFs struct {
	source Fs
}

func NewWriteOnlyFs(source Fs) Fs {
	return &WriteOnlyFs{source: source}
}

/*func (r *WriteOnlyFs) ReadDir(name string) ([]os.FileInfo, error) {
	return ReadDir(r.source, name)
}*/
func (r *WriteOnlyFs) ReadDir(name string) ([]os.FileInfo, error) {
	 return nil, nil
}
func (r *WriteOnlyFs) Chtimes(n string, a, m time.Time) error {
	return syscall.EPERM
}

func (r *WriteOnlyFs) Chmod(n string, m os.FileMode) error {
	return syscall.EPERM
}

func (r *WriteOnlyFs) Chown(n string, uid, gid int) error {
	return syscall.EPERM
}

func (r *WriteOnlyFs) Name() string {
	return "WriteOnlyFilter"
}

func (r *WriteOnlyFs) Stat(name string) (os.FileInfo, error) {
	return r.source.Stat(name)
}

func (r *WriteOnlyFs) LstatIfPossible(name string) (os.FileInfo, bool, error) {
	if lsf, ok := r.source.(Lstater); ok {
		return lsf.LstatIfPossible(name)
	}
	fi, err := r.Stat(name)
	return fi, false, err
}

func (r *WriteOnlyFs) SymlinkIfPossible(oldname, newname string) error {
	return &os.LinkError{Op: "symlink", Old: oldname, New: newname, Err: ErrNoSymlink}
}

func (r *WriteOnlyFs) ReadlinkIfPossible(name string) (string, error) {
	if srdr, ok := r.source.(LinkReader); ok {
		return srdr.ReadlinkIfPossible(name)
	}

	return "", &os.PathError{Op: "readlink", Path: name, Err: ErrNoReadlink}
}

func (r *WriteOnlyFs) Rename(o, n string) error {
	return syscall.EPERM
}

func (r *WriteOnlyFs) RemoveAll(p string) error {
	return syscall.EPERM
}

func (r *WriteOnlyFs) Remove(n string) error {
	return syscall.EPERM
}

func (r *WriteOnlyFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) {

	//if flag&(os.O_WRONLY|syscall.O_RDWR|os.O_APPEND|os.O_CREATE|os.O_TRUNC) != 0 {
	if flag == os.O_RDONLY {
		//表示下载时 进入返回
		return nil, syscall.EPERM
	}
	return r.source.OpenFile(name, flag, perm)
	//return nil, syscall.EPERM
}

func (r *WriteOnlyFs) Open(n string) (File, error) {
	//return nil,syscall.EPERM
	//文件目录系统 刷新或者进入下次目录是进入
	return r.source.Open(n)
}

func (r *WriteOnlyFs) Mkdir(name string, p os.FileMode) error {
	//return syscall.EPERM
	/*if name, err = b.RealPath(name); err != nil {
		return &os.PathError{Op: "mkdir", Path: name, Err: err}
	}*/
	return os.Mkdir(name, p)
}

func (r *WriteOnlyFs) MkdirAll(n string, p os.FileMode) error {
	return syscall.EPERM
}

func (r *WriteOnlyFs) Create(name string) (File, error) {
	//return nil, syscall.EPERM
	f, e := os.Create(name)
	if f == nil {
		// while this looks strange, we need to return a bare nil (of type nil) not
		// a nil value of type *os.File or nil won't be nil
		return nil, e
	}
	return f, e
}
